package com.web.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Random;

public class VerifyCodeUtil {
	/**
	 * 功能：按照传入的字符串生成验证码图片
	 * @param imageStr 需要生成验证码字符串
	 * @return 验证码图片
	 */
	public static Image createImage(String imageStr) {
		int width = 100, height = 30;
		//创建一张图片
		Image image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		//创建画笔画矩形
		Graphics g = image.getGraphics();
		g.setColor(Color.black);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.white);
		g.fillRect(1, 1, width-2, height-2);		
		//写字符
		g.setColor(Color.red);
		g.setFont(new Font("微软雅黑", Font.BOLD,  20));
		g.drawString(imageStr, 5, 25);
		
		//画干扰线
		Random random = new Random();
		for(int i = 0 ; i < 10 ; i ++){
			//设置随机颜色
			g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
			//随机画直线
			g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
		}
		return image;
	}	
	
	/**
	 * 功能：生成固定位数的随机字符串
	 * @param strNum 位数
	 * @return
	 */
	public static String createRandomStr(int strNum) {
		StringBuffer sb = new StringBuffer();
		String bufferStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		for(int i=0; i< strNum; i++) {
			int index = random.nextInt(36);
			sb.append(bufferStr.substring(index, index+1));
		}
		return sb.toString();
	}	
}
